package com.xhs.main.shiro;

import com.xhs.main.entity.yfb.YfbUser;
import com.xhs.main.service.yfb.YfbUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 认证和权限
 * @create 2020-10-24 18:46
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    YfbUserService yfbUserService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //2.查数据库，给该用户设置角色（可以根据表结构，决定要不要角色）
//        authorizationInfo.setRoles(yfbUserService.getRoles(username));
        //3.查数据库，给该用户设置权限
        authorizationInfo.setStringPermissions(yfbUserService.getPermissions(username));
        return authorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        //1.根据 Token 获取用户名
        String username = (String) token.getPrincipal();
        //2.根据用户名从数据库查询该用户(用户名唯一)
        YfbUser yfbUser = yfbUserService.queryUserByName(username);
        if (yfbUser != null) {
            //3.把当前用户存到session域中
            SecurityUtils.getSubject().getSession().setAttribute("user", yfbUser);
            //4.传入用户和密码进行身份认证，并返回认证信息
            AuthenticationInfo sai =
                    new SimpleAuthenticationInfo(yfbUser.getYfbUserUsername(), yfbUser.getYfbUserPassward(), this.getName());
            return sai;
        } else {
            return null;
        }
    }
}
